<template>
  <div class="exam-editor-container">
    <!-- ===== 问卷标题 ===== -->
    <header v-if="paperHeader" class="paper-header">
      <h1>{{ paperHeader.paper_title }}</h1>
      <p>{{ paperHeader.paper_content }}</p>
    </header>
    <div class="body-wrap">
      <!-- ===== 左侧题号索引 ===== -->
      <aside class="question-list">
        <div class="paper-notice" @click="selectNotice">
          <span>问卷须知</span>
        </div>
        <template v-for="(group, gIdx) in questionGroups" :key="gIdx">
          <p class="group-header">{{ group.title }}（{{ group.questions.length }} 题）</p>
          <ul>
           <li
                v-for="(q, qIdx) in group.questions"
                :key="q.qs_id + '_' + qIdx" 
                :class="{ active: currentQsId === q.qs_id }"
                @click="selectQuestion(q)"
                >
                <!-- 题号 -->
                <span class="nav-num">{{ gIdx + 1 }}.{{ qIdx + 1 }}</span>
                <!-- 纯文本题干 -->
                <span class="nav-text">{{ short(plain(q.qs_title)) }}</span>
           </li>
          </ul>
        </template>
      </aside>

      <!-- ===== 右侧题目区 ===== -->
      <main class="question-editor">

        <!-- 题目列表：一题一题竖向排列 -->
          <section
            v-for="(group, gIdx) in questionGroups"
            :key="gIdx"
            class="group-section"
          >
            <h3 class="group-title">{{ group.title }}</h3>

            <article
              v-for="(q, qIdx) in group.questions"
              :key="q.qs_id"
              :id="'q' + q.qs_id"
              class="question-block"
            >
             <p class="qs-title">
            <span class="qs-index">{{ gIdx + 1 }}.{{ qIdx + 1 }}</span>
            <span v-html="q.qs_title"></span>
            </p>
              <!-- 单选 -->
              <div v-if="q.qs_type === 'only_sel'||q.qs_type === 'yesorno'" class="options">
                <label v-for="opt in q.options" :key="opt.option_id" class="option-label">
                 <input
                    type="radio"
                    :name="'only_' + q.qs_id"
                    v-model="q.ans_id"
                    :value="opt.option_id"
                    :disabled="isFinished"
                />
                  {{ opt.option_content || opt.ans_content }}
                </label>
              </div>

              <!-- 多选 -->
              <div v-else-if="q.qs_type === 'many_sel'" class="options">
                <label v-for="opt in q.options" :key="opt.option_id" class="option-label">
                 <input
                    type="checkbox"
                    v-model="q.ans_ids"
                    :value="opt.option_id" 
                    :disabled="isFinished"
                />
                  {{ opt.option_content || opt.ans_content }}
                </label>
              </div>

              <!-- 简答 -->
              <div v-else class="options">
                <textarea
                  v-model="q.ans"
                  rows="4"
                  :readonly="isFinished"
                  placeholder="请输入答案"
                ></textarea>
              </div>
            </article>
          </section>
      </main>
    </div>

    <!-- ===== 底部提交按钮（仅未完成时显示） ===== -->
    <footer v-if="!isFinished" class="submit-bar">
      <button class="submit-btn" style="margin-right:60px"  @click="handleSubmit">提交问卷</button>
    </footer>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { ElMessage } from 'element-plus';
import {
  getSurveyDetail,
  getPaperDetails,
  getPaperHeader,
  submitSurvey
} from '@/services/api';

export default {
  name: 'StuServayDetail',
  setup() {
    /* ===== 路由参数 ===== */
    const route      = useRoute();
    const router     = useRouter();
    const paperId    = Number(route.params.paperId);
    const surveyId   = Number(route.query.surveyId || 0);
    const SSId   = Number(route.query.SSId || 0);
    const UserID = Number(localStorage.getItem('id'));
    const isFinished = route.query.isFinished === 'true' || route.query.isFinished === true;

    /* ===== 状态 ===== */
    const paperHeader     = ref(null);
    const questionGroups  = ref([]);
    const currentQsId     = ref(null); // 用于高亮左侧导航
    const showNotice      = ref(true);
    const plain = (html = '') => html.replace(/<[^>]+>/g, '').trim();
    const short = (txt, n = 18) =>
      txt.length > n ? txt.slice(0, n) + '…' : txt;
    const stripHtml = (str = '') => str.replace(/<[^>]+>/g, '');

    /* ===== 数据处理 ===== */
    const mapToGroups = raw => {
      const map = {
        only_sel: '一、【单选题】',
        many_sel: '二、【多选题】',
        yesorno:  '三、【判断题】',
        qna:      '四、【简答题】'
      };
      const groups = [];
      ['only_sel', 'many_sel', 'yesorno', 'qna'].forEach(tp => {
        const arr = raw.filter(q => q.qs_type === tp);
        if (arr.length) groups.push({ title: map[tp], questions: arr });
      });
      return groups;
    };

    /** 获取问卷头部信息 */
    const loadHeader = async () => {
      const { data } = await getPaperHeader(paperId);
      if (data.status === 1) paperHeader.value = data.data;
    };

    /** 获取题目（根据完成状态分流） */
    const loadQuestions = async () => {
      if (isFinished) {
        // 已完成：带答案
        const { data } = await getSurveyDetail({
          paper_id: paperId,
          survey_id: surveyId,
          survey_stu_id: SSId
        });
        if (data.status === 1) {
            const flattenDeep = (arr) =>
               arr.some(Array.isArray) ? flattenDeep(arr.flat()) : arr;
            const flatQs = flattenDeep(data.data.qsList);
            console.log(flatQs)
            const processed = flatQs.map(q => {
            if (q.qs_type === 'qna') {
                return { ...q, ans: q.stu_ans || '' };
            }
            if (q.qs_type === 'many_sel') {
                const ids = q.options.filter(o => o.stu_choosed).map(o => o.option_id);
                return { ...q, ans_ids: ids };
            }
            const chosen = q.options.find(o => o.stu_choosed);
            return { ...q, ans_id: chosen ? chosen.option_id : null };
            });

            questionGroups.value = mapToGroups(processed);
        }
      } else {
        // 未完成：仅题面
        const { data } = await getPaperDetails(paperId);
        if (data.status === 1) {
          questionGroups.value = data.data.paperList.map(g => ({
            title: g.format_content,
            questions: g.items.map(it => {
                if (['only_sel', 'yesorno'].includes(it.qs_type)) {
                return { ...it, ans_id: null };      // ⬅︎ 单选/判断题
                }
                if (it.qs_type === 'many_sel') {
                return { ...it, ans_ids: [] };       // ⬅︎ 多选题
                }
                return { ...it, ans: '' };             // ⬅︎ 简答
            })
         }));
        }
      }
      // 回到须知页
      showNotice.value = true;
      currentQsId.value = null;
    };

    /* ===== 交互方法 ===== */
    const selectNotice = () => {
      showNotice.value = true;
      currentQsId.value = null;
    };

    const selectQuestion = q => {
      showNotice.value = false;
      currentQsId.value = q.qs_id;
      nextTick(() => {
        const el = document.getElementById('q' + q.qs_id);
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      });
    };

    /** 提交问卷（仅在未完成时调用） */
    const handleSubmit = async () => {
      const payload = {
        paper_id: paperId,
        survey_id: surveyId,
        user_id: UserID,
        questions: questionGroups.value.flatMap(g =>
        g.questions.map(q => {
            if (q.qs_type === 'qna') {
                return { qs_id: q.qs_id, qs_type: q.qs_type, ans: q.ans || '' };
            }
            if (q.qs_type === 'many_sel') {
                // 数组里只保留已选答案
                return {
                qs_id: q.qs_id,
                qs_type: q.qs_type,
                ans_ids: (q.ans_ids || []).map(Number)
                };
            }
            // only_sel / yesorno
            return {
                qs_id: q.qs_id,
                qs_type: q.qs_type,
                ans_ids: q.ans_id != null ? [Number(q.ans_id)] : []
            };
            })
        )
        };

      const { data } = await submitSurvey(payload);
      if (data.status === 1) {
        ElMessage.success('提交成功');
        // 提交成功后重载本页，改成“已完成”模式
        router.replace({
          name: 'StuServayDetail',
          params: { paperId },
          query: { surveyId, isFinished: true }
        });
      } else {
        ElMessage.error('提交失败：' + data.msg);
      }
    };

    /* ===== 生命周期 ===== */
    onMounted(async () => {
      await loadHeader();
      await loadQuestions();
    });

    /* ===== 向模板暴露 ===== */
    return {
      paperHeader,
      questionGroups,
      currentQsId,
      showNotice,
      isFinished,
      stripHtml,
      selectNotice,
      selectQuestion,
      handleSubmit,
      plain,
      short
    };
  }
};
</script>

<style scoped>
/***** 整体布局 *****/
.exam-editor-container { display:flex; flex-direction:column; background:#f5f6fa; height:100vh; }
.body-wrap              { display:flex; flex:1; overflow:hidden; }

/***** 头部 *****/
.paper-header          { background:#2f80ed; color:#fff; padding:18px 0; text-align:center; }
.paper-header h1       { font-size:22px; font-weight:bold; }

/***** 左侧索引 *****/
.question-list         { width:25%; background:#fff; padding:20px; overflow-y:auto; border-right:1px solid #e5e5e5; }
.group-header          { font-weight:bold; margin:15px 0 6px; }
.question-list ul      { list-style:none; padding-left:0; }
.question-list li{  
  align-items: center;
  gap: 6px;
  display:flex;
  justify-content:space-between; 
  padding:10px; 
  border-radius:6px; 
  margin-bottom:6px; 
  cursor:pointer; 
  background:#f9f9f9; 
  transition:.2s; 
  }
.nav-num  { font-weight: 600; color: #244382; }
.nav-text { flex: 1; color: #555; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.question-list li.active,
.question-list li:hover { background:#eff5ff; }
.paper-notice          { font-weight:bold; margin-bottom:12px; cursor:pointer; background:#f7f9fc; padding:10px; border-radius:6px; }

/***** 右侧题目区 *****/
.question-editor                     { flex:1; background:#fff; overflow:auto; padding:24px 40px; }
.group-section                       { margin-bottom:36px; }
.group-title                         { font-size:18px; font-weight:bold; margin-bottom:16px; }
.question-block {
  background: #fafbff;
  border: 1px solid #e7e9f3;
  border-radius: 8px;
  padding: 18px 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0,0,0,.04);
}
.question-block:last-of-type {
  margin-bottom: 0;
}
.qs-index {
  color: #244382;
  font-weight: 600;
  margin-right: 8px;
}
.qs-title {
  display: flex;
  align-items: center;
  font-size: 17px;
  height: 0px;
  font-weight: 600;
  color: #244382;
}
.options                             { margin-left:12px; }
.option-label {
  position: relative;
  display: flex;
  align-items: center;
  padding: 6px 0;
  cursor: pointer;
  transition: background .2s;
}
.option-label:hover {
  background: #f3f6ff;
}
.option-label input {
  margin-right: 6px;
}
textarea                             { width:100%; padding:8px; font-size:14px; resize:vertical; }

/***** 底部提交栏 *****/
.submit-bar { background:#fff; border-top:1px solid #eee; padding:12px 0; text-align:end; }
.submit-btn { transition: background .25s, transform .25s;background:#2f80ed; color:#fff; border:none; padding:10px 24px; border-radius:4px; cursor:pointer; font-size:15px; }
.submit-btn:hover {
  background: #1c6ce3;
  transform: translateY(-1px);
}

/***** 滚动条美化 *****/
.question-list::-webkit-scrollbar       { width:6px; }
.question-list::-webkit-scrollbar-thumb { background:#c8c8c8; border-radius:3px; }
</style>
